<!--  -->
<template>
  <div class="container">
    <cu-custom
      :bgImage="bgImage"
      :needBack="true"
      bgColor="bgNormal"
      topTitle="在线咨询"
      titleClass="commTitleWhite"
      backIconColor="#fff"
    ></cu-custom>
    <view class="content" :style="{ height: contentHeight }">
      <scroll-view
        class="cu-chat"
        :scroll-y="true"
        :style="{ height: scorllContentHeight }"
        :scroll-with-animation="true"
        :scroll-top="scrollTop"
      >
        <view class="artificial_intelligence_container">
          <view class="artificial_intelligence">
            <image src="@/static/images/kefu.png"></image>
            <text class=""> 人工智能 </text>
            <text class="">
              {{ $u.timeFormat(new Date().getTime(), "yyyy-mm-dd hh:MM:ss") }}
            </text>
          </view>
          <view class="context">
            <view class="context_tips">
              您好，欢迎方位社会组织申报评估 小程序！我是小爱，很高兴为您服 务！
            </view>
            <view class="" @click="handleSearch('如何咨询')"> 如何咨询 </view>
            <view class="" @click="handleSearch('怎么上传资料')">
              怎么上传资料
            </view>
            <view class="" @click="handleSearch('转人工客服')">
              转人工客服
            </view>
          </view>
          <view
            class="que_ans"
            v-for="(item, index) in questionAndAnswesList"
            :key="index"
          >
            <view
              class="que_ans_info"
              :style="{
                display: 'flex',
                justifyContent: item.tag === 'my' ? 'flex-end' : 'flex-start',
                alignItems: 'center',
              }"
            >
              <image :src="item.url" v-if="item.tag !== 'my'"></image>
              <view>
                {{ item.name }}
              </view>
              <view class="">{{ item.time }}</view>
            </view>
            <view :class="item.tag === 'my' ? 'my' : 'robot'">
              <view class="content">
                <view class="">
                  {{ item.content }}
                </view>
                <view class="" style="text-align: center">
                  <image
                    v-if="item.img"
                    class=""
                    :src="item.img"
                    style="width: 358rpx; height: 358rpx; margin-top: 20rpx"
                    @longtap="handleSave(item.img)"
                  >
                  </image>
                </view>
                <view
                  v-if="item.tag !== 'my' && Object.keys(item.file).length"
                  class="attachment"
                >
                  <view class="attachment_reply">此答复包含附件</view>
                  <view class="attachment_btn">
                    <u-button
                      type="primary"
                      plain
                      @click="handlePreview(item.file)"
                      hover-class="none"
                      size="mini"
                      >查看</u-button
                    >
                    <!-- <u-button
                      type="primary"
                      plain
                      style="margin-left: 20px"
                      @click="handleUpload"
                      hover-class="none"
                      size="mini"
                      >下载</u-button
                    > -->
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="search">
        <u-input
          placeholder=" "
          v-model="keyword"
          height="88"
          :clearable="false"
        ></u-input>
        <view class="" @click="handleSend(keyword)"> 发送 </view>
      </view>
    </view>
  </div>
</template>

<script>
import { quickReply, getLeaveMessageList } from "@/api/my";
export default {
  data() {
    return {
      keyword: "", // 搜索关键词
      contentHeight: "", // 页面可用高度
      scorllContentHeight: "", // 页面滚动高度
      questionAndAnswesList: [], // 问题与回复列表
      userInfo: {}, // 用户信息
      scrollTop: 0, // 滚动条的位置
    };
  },
  onShow() {
    this.getHeight();
    this.getLeaveMessageList();
    this.userInfo = uni.getStorageSync("userInfo");
  },
  methods: {
    getLeaveMessageList() {
      getLeaveMessageList({ size: 9999, current: 1, type: 2 }).then((res) => {
        if (res.code == 200) {
          // console.log("message===", res);
          res.data &&
            res.data.records &&
            res.data.records.forEach((item) => {
              this.questionAndAnswesList.push({
                time: item.createTime,
                name: this.userInfo.userName,
                content: item.message,
                tag: "my",
              });
              if (
                item.leaveMessageReplyList &&
                item.leaveMessageReplyList.length
              ) {
                item.leaveMessageReplyList.forEach((message) => {
                  this.questionAndAnswesList.push({
                    time: item.replyTime,
                    name: "人工智能",
                    file: message.fileUrl ? message : {}, // 文件
                    content: message.reply,
                    url: require("@/static/images/kefu.png"),
                  });
                });
              } else {
                this.questionAndAnswesList.push({
                  time: item.createTime,
                  name: "人工智能",
                  file: {},
                  content: "转人工客服(长按图片保存至本地)",
                  img: require("@/static/images/qq.jpg"),
                  url: require("@/static/images/kefu.png"),
                });
              }
            });
          this.scrollTop = 999999;
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
    },
    // 动态计算滚动高度
    getHeight() {
      this.contentHeight = `calc(100vh - ${this.CustomBar}px)`;
      this.scorllContentHeight = `calc(100vh - ${this.CustomBar}px - 108rpx - 42rpx - 20rpx)`;
    },
    handleSearch(val) {
      this.handleSend(val);
    },
    // 发送
    handleSend(val) {
      // console.log(val);
      this.questionAndAnswesList.push({
        time: this.$u.timeFormat(new Date().getTime(), "yyyy-mm-dd hh:MM:ss"),
        name: this.userInfo.userName,
        content: val,
        tag: "my",
      });
      quickReply({ keyWord: val }).then((res) => {
        if (res.code == 200) {
          // console.log("res==", res);
          if (res.data.length) {
            res.data.forEach((item) => {
              this.questionAndAnswesList.push({
                time: this.$u.timeFormat(
                  new Date().getTime(),
                  "yyyy-mm-dd hh:MM:ss"
                ),
                name: "人工智能",
                file:
                  item.file && Object.keys(item.file).length ? item.file : {},
                content: item.replyContent,
                url: require("@/static/images/kefu.png"),
              });
              this.scrollTop = this.scrollTop + 1;
            });
          } else {
            this.questionAndAnswesList.push({
              time: this.$u.timeFormat(
                new Date().getTime(),
                "yyyy-mm-dd hh:MM:ss"
              ),
              name: "人工智能",
              file: {},
              content: "转人工客服",
              img: require("@/static/images/qq.jpg"),
              url: require("@/static/images/kefu.png"),
            });
            this.scrollTop = this.scrollTop + 1;
          }
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
      this.keyword = "";
    },
    // 长按保存
    handleSave(url) {
      uni.showLoading({
        title: "正在保存图片...",
      });
      //获取用户的当前设置。获取相册权限
      uni.getSetting({
        success: (res) => {
          //如果没有相册权限
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            //向用户发起授权请求
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success: () => {
                //授权成功保存图片到系统相册
                wx.getImageInfo({
                  src: url,
                  success: function (sres) {
                    // console.log(sres.path);
                    uni.saveImageToPhotosAlbum({
                      filePath: sres.path,
                      success: (res) => {
                        uni.hideLoading();
                        return uni.showToast({
                          title: "保存成功！",
                        });
                      },
                      fail: (res) => {
                        uni.hideLoading();
                        // console.log(res.errMsg);
                        return uni.showToast({
                          title: res.errMsg,
                          icon: "none",
                        });
                      },
                      //无论成功失败都走的回调
                      complete: (res) => {
                        uni.hideLoading();
                      },
                    });
                  },
                });
              },
              //授权失败
              fail: () => {
                uni.hideLoading();
                uni.showModal({
                  title: "您已拒绝获取相册权限",
                  content: "是否进入权限管理，调整授权？",
                  success: (res) => {
                    if (res.confirm) {
                      //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                      uni.openSetting({
                        success: (res) => {
                          // console.log(res.authSetting);
                        },
                      });
                    } else if (res.cancel) {
                      return uni.showToast({
                        title: "已取消！",
                        icon: "none",
                      });
                    }
                  },
                });
              },
            });
          } else {
            //如果已有相册权限，直接保存图片到系统相册
            wx.getImageInfo({
              src: url,
              success: function (sres) {
                // console.log(sres.path);
                uni.saveImageToPhotosAlbum({
                  filePath: sres.path,
                  success: (res) => {
                    uni.hideLoading();
                    return uni.showToast({
                      title: "保存成功！",
                    });
                  },
                  fail: (res) => {
                    uni.hideLoading();
                    console.log(res.errMsg);
                    return uni.showToast({
                      title: res.errMsg,
                      icon: "none",
                    });
                  },
                  //无论成功失败都走的回调
                  complete: (res) => {
                    uni.hideLoading();
                  },
                });
              },
            });
          }
        },
        fail: (res) => {},
      });
    },
    handlePreview(file) {
      const url = file.fileUrl || file.url;
      if (url.includes("pdf") || url.includes("docx")) {
        uni.downloadFile({
          url,
          success: function (res) {
            // console.log(res);
            var filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {
                // console.log("打开文档成功");
              },
            });
          },
        });
      } else {
        uni.previewImage({
          current: 0,
          urls: [url],
        });
      }
    },
    handleUpload() {
      if (
        this.file.type == "doc" ||
        this.file.type == "docx" ||
        this.file.type == "pdf"
      ) {
        uni.showLoading({
          title: "文件下载中",
          mask: true,
        });
        uni.downloadFile({
          url: this.file.url,
          success: (res) => {
            const path = res.tempFilePath;
            uni.openDocument({
              filePath: path,
              success: () => {
                uni.showToast({ title: "下载成功", icon: "none" });
                uni.hideLoading();
              },
            });
          },
          fail: (fail) => {
            uni.showToast({ title: "下载失败", icon: "none" });
            uni.hideLoading();
          },
        });
      } else {
        uni.showLoading({
          title: "图片保存中",
          mask: true,
        });
        uni.downloadFile({
          url: this.file.url,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  uni.showToast({
                    title: "保存成功"
                  });
                  uni.hideLoading();
                },
                fail: function () {
                  uni.showToast({
                    title: "保存失败",
                    icon: "none",
                  });
                  uni.hideLoading();
                },
              });
            } else {
              uni.showToast({
                title: "保存失败",
                icon: "none",
              });
              uni.hideLoading();
            }
          },
        });
      }
    },
  },
  components: {},
};
</script>
<style lang="scss"  scoped>
.container {
  background: #f2f2f2;
  font-size: 24rpx;
  color: #666;
  .content {
    padding-top: 45rpx;
    .artificial_intelligence_container {
      padding: 0 30rpx;
      .artificial_intelligence {
        display: flex;
        align-items: center;
        image {
          width: 84rpx;
          height: 84rpx;
        }
        text {
          margin-left: 19rpx;
        }
      }
    }

    .context {
      width: 470rpx;
      margin-left: 104rpx;
      background: #fff;
      padding: 31rpx 26rpx 53rpx;
      font-size: 26rpx;
      color: #1481ff;
      border-radius: 30rpx;
      border-top-left-radius: 0;
      .context_tips {
        line-height: 36rpx;
        font-size: 28rpx;
        color: #4a4a4a;
      }
      view {
        color: #1481ff;
        font-size: 26rpx;
        &:nth-child(n + 2) {
          margin-top: 30rpx;
        }
      }
    }
    .que_ans {
      margin-top: 71rpx;
      .que_ans_info {
        image {
          width: 84rpx;
          height: 84rpx;
        }
        view {
          &:nth-child(n + 1) {
            margin-left: 19rpx;
          }
        }
      }
      .my {
        display: flex;
        justify-content: flex-end;
        .content {
          margin-top: 26rpx;
          background: linear-gradient(90deg, #417ffc, #505eeb);
          box-shadow: 0rpx 6rpx 10rpx 0rpx rgba(22, 121, 253, 0.28);
          padding: 24rpx 37rpx 26rpx 34rpx;
          font-size: 28rpx;
          color: #fff;
          max-width: 80%;
          overflow: hidden;
          border-radius: 30rpx;
          border-top-right-radius: 0;
        }
      }
      .robot {
        .content {
          margin-top: 26rpx;
          background: #fff;
          padding: 31rpx 26rpx 53rpx;
          width: 470rpx;
          line-height: 36rpx;
          font-size: 28rpx;
          color: #4a4a4a;
          border-radius: 30rpx;
          border-top-left-radius: 0;
          margin-left: 104rpx;
        }
      }
    }
    .search {
      position: fixed;
      background: #fff;
      bottom: 20rpx;
      left: 30rpx;
      right: 30rpx;
      border-radius: 10rpx;
      padding-left: 10rpx;
      padding-right: 35rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      view {
        font-size: 32rpx;
        color: #427efc;
      }
    }
  }
}
.attachment {
  .attachment_reply {
    line-height: 70rpx;
    border-top: 1px solid #ccc;
  }
  .attachment_btn {
    display: flex;
  }
}
</style>